package com.mylearn.myblog.service.impl;

import com.mylearn.myblog.dao.BlogRepository;
import com.mylearn.myblog.entity.Blog;
import com.mylearn.myblog.service.BlogService;
import javassist.NotFoundException;
import org.aspectj.lang.annotation.AfterReturning;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BlogServiceImpl implements BlogService {

	@Autowired
	private BlogRepository blogRepository;

	@Override
	public Blog getBlog(Long id) {
		return blogRepository.getOne(id);
	}

	/**
	 * Root查询表的字段；CriteriaQuery存放查询字段；CriteriaBuilder设置具体某一条件表达式
	 * @param pageable
	 * @param blog
	 * @return
	 */
	@Override
	public Page<Blog> listBlog(Pageable pageable, Blog blog) {
		return blogRepository.findAll(new Specification<Blog>() {
			@Override
			public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();
				if (!"".equals(blog.getTitle())&&blog.getTitle()!=null){
					predicates.add(cb.like(root.<String>get("title"),"%"+blog.getTitle()+"%"));
				}
				if (blog.getType()!=null && blog.getType().getId()!=null){
					predicates.add(cb.equal(root.<String>get("type").get("id"),blog.getType().getId()));
				}
				if (blog.isRecommend()){
					predicates.add(cb.equal(root.<Boolean>get("recommend"),blog.isCommentabled()));
				}
				cq.where(predicates.toArray(new Predicate[predicates.size()]));//此处将集合转为数组进行拼接条件
				return null;
			}
		},pageable);
	}

	@Override
	public Blog saveBlog(Blog blog) {
		blog.setCreateTime(new Date());
		blog.setUpdateTime(new Date());
		return blogRepository.save(blog);
	}

	@Override
	public Blog updateBlog(Long id, Blog blog) {
		Blog b = blogRepository.getOne(id);
		if (b == null){
			try {
				throw new NotFoundException("Id 不存在");
			} catch (NotFoundException e) {
				e.printStackTrace();
			}
		}
		BeanUtils.copyProperties(blog,b);
		b.setId(id);
		return blogRepository.saveAndFlush(b);
	}

	@Override
	public void deleteBlog(Long id) {
		blogRepository.deleteById(id);
	}

	@Override
	public Blog getBlogByTitle(String title) {
		return blogRepository.findBlogByTitle(title);
	}
}
